<?php

namespace App\Http\Controllers\Mobile;

use App\Models\Order;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class BoughtController extends Controller
{
    //
    public function index()
    {

        $this->assign(['tradeStatus'=>intval($this->request->get('tradeStatus'))]);
        return $this->view('mobile.trade.bought');
    }

    public function getjson()
    {
        $offset = $this->request->input('offset');
        $count  = $this->request->input('count');
        $offset = $offset ? $offset : 0;
        $count  = $count ? $count : 20;

        $query = Order::with(['items'])->where('buyer_uid', $this->uid)->where('buyer_deleted', 0);

        $tradeStatus = $this->request->input('tradeStatus');
        if ($tradeStatus) {
            $query = $query->where('trade_status', $tradeStatus);
        }

        $tradeStatusItems = trans('mall.seller_trade_status_items');
        $orders =$query->offset($offset)->limit($count)->orderByDesc('order_id')
            ->get()->map(function ($order) use ($tradeStatusItems){
                $order->tradeStatusText = $tradeStatusItems[$order->trade_status];
                $order->items = $order->items->map(function ($item){
                    $item->thumb = image_url($item->thumb);
                    $item->image = image_url($item->image);
                    return $item;
                });
                return $order;
            });

        return ajaxReturn(['orders'=>$orders]);
    }

    public function detail()
    {
        $order_id = $this->request->input('order_id');
        $order = Order::find($order_id);
        if ($order) {
            $shipping = $order->shipping;
            $items = $order->items;

            $this->assign(compact('order_id', 'order', 'shipping', 'items'));
            return $this->view('mobile.trade.detail');
        } else {
            return ajaxError(404, trans('mall.order does not exist'));
        }
    }

    public function closeOrder()
    {
        $order_id = $this->request->input('order_id');
        $order = Order::where('buyer_uid', $this->uid)->where('order_id',$order_id)->first();
        if ($order && $order->trade_status == 1) {
            $order->close();
        }
        return ajaxReturn();
    }
}
